﻿using CheemsControl.Animations;
using CheemsControl.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Intrinsics.X86;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CheemsControl.Controls
{
    public class VirtualModelOfProductionLine : UserControl
    {
        public VirtualModelOfProductionLine()
        {
            this.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x55, 0x55, 0x55));
        }



        /// <summary>
        /// 产线提示信息
        /// </summary>
        public ProductionLineData Source
        {
            get { return (ProductionLineData)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(ProductionLineData), typeof(VirtualModelOfProductionLine), new PropertyMetadata(null, OnSourceChanged));


        /// <summary>
        /// 产线背景色
        /// </summary>
        public Brush ProductionLineBackground
        {
            get { return (Brush)GetValue(ProductionLineBackgroundProperty); }
            set { SetValue(ProductionLineBackgroundProperty, value); }
        }
        public static readonly DependencyProperty ProductionLineBackgroundProperty =
            DependencyProperty.Register("ProductionLineBackground", typeof(Brush), typeof(VirtualModelOfProductionLine), new PropertyMetadata(new SolidColorBrush(Color.FromArgb(0xFF, 0xCC, 0xCC, 0xCC))));

        /// <summary>
        /// 产线边框色
        /// </summary>
        public Brush ProductionLineBroderBrush
        {
            get { return (Brush)GetValue(ProductionLineBroderBrushProperty); }
            set { SetValue(ProductionLineBroderBrushProperty, value); }
        }
        public static readonly DependencyProperty ProductionLineBroderBrushProperty =
            DependencyProperty.Register("ProductionLineBroderBrush", typeof(Brush), typeof(VirtualModelOfProductionLine), new PropertyMetadata(new SolidColorBrush(Color.FromArgb(0xFF, 0x88, 0x88, 0x88))));

        /// <summary>
        /// 产线边框粗细
        /// </summary>
        public double ProductionLineBorderThickness
        {
            get { return (double)GetValue(ProductionLineBorderThicknessProperty); }
            set { SetValue(ProductionLineBorderThicknessProperty, value); }
        }
        public static readonly DependencyProperty ProductionLineBorderThicknessProperty =
            DependencyProperty.Register("ProductionLineBorderThickness", typeof(double), typeof(VirtualModelOfProductionLine), new PropertyMetadata(1.0));


        /// <summary>
        /// 数据改变时触发
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            #region 设置
            double margin = 10;
            double canvasWidth = 520;
            double picWidth = 80;
            double lineWidth = 4;
            double valueWidth = 40;
            #endregion

            VirtualModelOfProductionLine thisControl = d as VirtualModelOfProductionLine;
            Viewbox viewbox = new Viewbox();
            Canvas canvas = new Canvas()
            {
                Width = canvasWidth,
                Height = 160,
            };
            #region 绘制产线方块
            Border block = new Border()
            {
                Background = thisControl.ProductionLineBackground,
                BorderBrush = thisControl.BorderBrush,
                BorderThickness = new Thickness(thisControl.ProductionLineBorderThickness),
                Width = canvas.Width - margin * 2,
                Height = 100,
                Margin = new Thickness(margin, margin * 2, margin, margin * 2),
                CornerRadius = new CornerRadius(5),
            };
            canvas.Children.Add(block);
            #endregion
            #region 绘制产线位置数字标识
            double len = thisControl.Source.maxPosition - thisControl.Source.minPosition;
            double step = len / 8;
            for (int i = 0; i < 9; i++)
            {
                double value = Math.Round(i * step / 10) * 10 + thisControl.Source.minPosition;
                double valuePosition = GetControlPosition(value, valueWidth, thisControl.Source.minPosition, thisControl.Source.maxPosition, canvasWidth, margin);

                Border border = new Border()
                {
                    Width = valueWidth,
                    Height = 20,
                };

                TextBlock textBlock = new TextBlock()
                {
                    Text = value.ToString(),
                    FontSize = 12,
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Foreground = thisControl.BorderBrush,
                };
                border.Child = textBlock;
                Canvas.SetLeft(border, valuePosition);
                Canvas.SetTop(border, 0);
                canvas.Children.Add(border);
            }
            #endregion
            #region 绘制整百标识
            for (double i = thisControl.Source.minPosition; i < thisControl.Source.maxPosition; i+=100)
            {
                double WholeHundredValue = Math.Round(i/100, 0) * 100;
                if (WholeHundredValue > thisControl.Source.minPosition + 30 && WholeHundredValue < thisControl.Source.maxPosition - 30)
                {
                    double WholeHundredValuePosition = GetControlPosition(WholeHundredValue, valueWidth, thisControl.Source.minPosition, thisControl.Source.maxPosition, canvasWidth, margin);
                    Border border = new Border()
                    {
                        Width = valueWidth,
                        Height = 20,
                        Opacity = 0.5
                    };
                    TextBlock textBlock = new TextBlock()
                    {
                        Text = WholeHundredValue.ToString(),
                        FontSize = 16,
                        FontWeight = FontWeights.Bold,
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Foreground = thisControl.BorderBrush,
                        ToolTip = $"位置标识，当前位置：{WholeHundredValue}",
                    };
                    border.Child = textBlock;
                    Canvas.SetLeft(border, WholeHundredValuePosition);
                    Canvas.SetTop(border, 60);
                    canvas.Children.Add(border);
                }
            }
            #endregion
            #region 绘制图片

            for (int i = 0; i < thisControl.Source.reminderInformations.Count; i++)
            {
                int num = i;
                double picPosition = GetControlPosition(thisControl.Source.reminderInformations[i].position, picWidth, thisControl.Source.minPosition, thisControl.Source.maxPosition, canvasWidth, margin);
                double linePosition = GetControlPosition(thisControl.Source.reminderInformations[i].position, lineWidth, thisControl.Source.minPosition, thisControl.Source.maxPosition, canvasWidth, margin);
                #region 报警颜色确认
                Brush tipColor;
                switch (thisControl.Source.reminderInformations[i].tipType)
                {
                    case TipType.None:
                        tipColor = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0x66, 0x4B, 0xB1, 0x5D)); // 谷歌绿
                        break;
                    case TipType.Warning:
                        tipColor = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0x66, 0xFB, 0xBC, 0x05)); // 谷歌黄
                        break;
                    case TipType.Alarm:
                        tipColor = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0x66, 0xEA, 0x42, 0x35)); // 谷歌红
                        break;
                    default:
                        tipColor = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0x66, 0x4B, 0xB1, 0x5D)); // 谷歌绿
                        break;
                }
                #endregion
                #region 绘制线
                // 动态创建 Path 和 LineGeometry
                Path linePath = new Path
                {
                    Stroke = tipColor,
                    StrokeThickness = lineWidth,
                    Data = new LineGeometry(new Point(linePosition, 20), new Point(linePosition, 110))
                };
                canvas.Children.Add(linePath);
                #endregion
                #region 绘制图
                Border border = new Border()
                {
                    Background = tipColor,
                    CornerRadius = new CornerRadius(5),
                    Width = picWidth,
                };
                Image image = new Image()
                {
                    ToolTip = $"位置：{thisControl.Source.reminderInformations[i].position}\n图片路径：{thisControl.Source.reminderInformations[i].source}",
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Margin = new Thickness(3),
                };
                image.Source = new BitmapImage(new Uri(thisControl.Source.reminderInformations[i].source));
                image.MouseLeftButtonDown += (sender, e) =>
                {
                    OpenFolderContainingImage(thisControl.Source.reminderInformations[num].source);
                };

                border.Child = image;
                Canvas.SetLeft(border, picPosition);
                Canvas.SetTop(border, 100);
                AnimationHelper.ApplyMouseEnterAnimation(border, border.Width / 2, 30, 1.5,0.05);

                canvas.Children.Add(border);
                #endregion

            }
            #endregion
            viewbox.Child = canvas;
            thisControl.Content = viewbox;
        }

        /// <summary>
        /// 打开文件夹并选中文件
        /// </summary>
        /// <param name="imagePath"></param>
        private static void OpenFolderContainingImage(string imagePath)
        {
            // 替换正斜杠为反斜杠
            string correctedPath = imagePath.Replace('/', '\\');
            if (!System.IO.File.Exists(imagePath))
            {
                MessageBox.Show("文件不存在，请检查路径。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                string argument = $"/select,\"{correctedPath}\"";
                Process.Start("explorer.exe", argument);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开文件夹: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 计算图片在画布中的位置
        /// </summary>
        /// <param name="position"></param>
        /// <param name="picWidth">图片自身宽度</param>
        /// <param name="minPosition"></param>
        /// <param name="maxPosition"></param>
        /// <param name="canvasWidth"></param>
        /// <param name="margin"></param>
        /// <returns></returns>
        private static double GetControlPosition(double position,double picWidth, double minPosition, double maxPosition, double canvasWidth, double margin = 10)
        {
            double canvasPosition = 0;
            double k = (position - minPosition) / (maxPosition - minPosition);
            double increment = (canvasWidth - (margin * 2)) * k;
            canvasPosition = margin + increment - picWidth / 2;

            return canvasPosition;
        }
    }
}
